<script setup lang="ts">
  import { ref, watch } from 'vue';
  import {
    queryDeviceAlarmOrderDetail,
    closeDeviceAlarmOrder,
    genOfflineOrderImageUploadToken,
  } from '@/api/workorder-management/alarm';
  import { useForm } from '@/hooks/arco/useForm';
  import { useModalHandler } from '@/hooks/arco/useModalHandler';
  import { useUploader } from '@/hooks/useUploader';
  import DispatchOrder from './dispatch-order.vue';

  const props = defineProps({
    orderId: {
      type: String,
      default: '',
    },
  });

  const baseNameMap = {
    id: { key: 'id', label: '' },
    orderId: { key: 'orderId', label: '' },
    handleMethod: {
      key: 'handleMethod',
      label: '处理方式',
      placeholder: '请输入处理方式',
    },
    handleResult: {
      key: 'handleResult',
      label: '处理结果',
      placeholder: '请输入处理结果',
    },
    images: { key: 'images', label: '现场照片（非必填）', placeholder: '' },
    addtions: {
      key: 'addtions',
      label: '补充说明（非必填）',
      placeholder: '可以在这里补充工单处理的说明内容',
    },
    // handleResult: {key: 'handleResult', label: '', placeholder: ''},
  };

  const loading = ref(false);
  const currentStep = ref(-1);
  const dataAlarm = ref<any>({});
  const additions = ref<any[]>([]);
  const siteImages = ref<any[]>([]);

  const getOrderDetails = () => {
    queryDeviceAlarmOrderDetail(props.orderId)
      .then((res) => {
        console.log(res);
        dataAlarm.value = res;
        if (res.resources) {
          additions.value = res.resources.voices;
          siteImages.value = res.resources.images;
        }
        currentStep.value = res.status;
      })
      .catch((err) => {});
  };

  const uploader = useUploader({
    apiFun: genOfflineOrderImageUploadToken,
  });

  const dataForm = useForm({
    state: {
      [baseNameMap.handleMethod.key]: '',
      [baseNameMap.handleResult.key]: '',
      [baseNameMap.images.key]: [] as any[],
      [baseNameMap.addtions.key]: '',
    } as any,
    rules: {
      [baseNameMap.handleMethod.key]: [
        {
          required: true,
          message: baseNameMap.handleMethod.placeholder,
        },
      ],
      [baseNameMap.handleResult.key]: [
        {
          required: true,
          message: baseNameMap.handleResult.placeholder,
        },
      ],
    },
  });

  const drawerHandler = ref({
    visible: false,
    show: () => {
      drawerHandler.value.visible = true;
      dataForm.backToInit();
    },
    onCancel: () => {
      drawerHandler.value.visible = false;
    },
    onOk: async () => {
      await dataForm.validate();
      loading.value = true;
      const state = dataForm.state as any;
      const data = {
        [baseNameMap.orderId.key]: dataAlarm.value[baseNameMap.id.key],
        [baseNameMap.handleMethod.key]: state[baseNameMap.handleMethod.key],
        [baseNameMap.handleResult.key]: state[baseNameMap.handleResult.key],
        remark: state[baseNameMap.addtions.key],
        resources: uploader.getResourceIds(),
      };
      // console.log(state, dataAlarm.value)
      // console.log(data);
      closeDeviceAlarmOrder(data)
        .then((res) => {
          console.log('close res:', res);
          getOrderDetails();
          drawerHandler.value.onCancel();
        })
        .catch((err) => {})
        .finally(() => {
          loading.value = false;
        });
      // const model = form.model as any;
      // form.validate().then(() => {
      //   console.log(model);
      // });
      // drawerHandler.value.visible = false;
    },
  });

  const dispatchOrderHandler = useModalHandler({
    onSuccess: (data) => {
      // dispatchOrderHandler
      getOrderDetails();
    },
  });

  watch(
    () => props.orderId,
    (newVal) => {
      if (newVal) {
        getOrderDetails();
      }
    },
    { immediate: true }
  );
</script>

<template>
  <div class="m-alarm-details flex-col flex-vcenter">
    <div class="m-alarm-d-steps" style="width: 800px; margin-top: 10px">
      <a-steps type="arrow" :current="currentStep">
        <a-step
          :description="`报警时间  ${
            dataAlarm.createdAt ? dataAlarm.createdAt : '--'
          }`"
          >待接单</a-step
        >
        <a-step
          :description="`接单时间  ${
            currentStep >= 2 ? dataAlarm.assignedAt : '--'
          }`"
          >已接单</a-step
        >
        <a-step
          :description="`完结时间  ${
            currentStep === 3 ? dataAlarm.closedAt : '--'
          }`"
          >已完结</a-step
        >
      </a-steps>
    </div>
    <div class="m-alarm-d-body" style="flex: 1; padding-top: 20px">
      <a-skeleton :animation="true">
        <table class="ma-table">
          <tr class="ma-table-title">
            <td colspan="6">
              <span v-if="dataAlarm.eventName">{{ dataAlarm.eventName }}</span>
              <!-- <a-skeleton-line v-else/> -->
            </td>
          </tr>
          <tr>
            <td class="label">报警人</td>
            <td class="value">
              <span v-if="dataAlarm.elderName">{{ dataAlarm.elderName }}</span>
              <!-- <a-skeleton-line /> -->
            </td>
            <td class="label">联系电话</td>
            <td class="value">
              <span v-if="dataAlarm.elderPhone">{{
                dataAlarm.elderPhone
              }}</span>
            </td>
          </tr>
          <tr>
            <td class="label">家庭地址</td>
            <td class="value">
              <span v-if="dataAlarm.elderAddress">{{
                dataAlarm.elderAddress
              }}</span>
            </td>
            <td class="label">关联站点</td>
            <td class="value">
              <span v-if="dataAlarm.assignStationName">{{
                dataAlarm.assignStationName
              }}</span>
            </td>
          </tr>
          <tr>
            <td class="label">报警设备</td>
            <td class="value">
              <span v-if="dataAlarm.deviceName">{{
                dataAlarm.deviceName
              }}</span>
            </td>
            <td class="label">接单人</td>
            <td class="value">
              <span
                v-if="currentStep === 1"
                style="
                  cursor: pointer;
                  color: rgb(var(--primary-6));
                  text-decoration: underline;
                  user-select: none;
                "
                @click="dispatchOrderHandler.showModal(dataAlarm)"
                >派单</span
              >
              <span v-else>{{ dataAlarm.assignStaffName }}</span>
            </td>
          </tr>
          <tr class="ma-table-title">
            <td colspan="6">家庭成员</td>
          </tr>
          <tr>
            <td class="label">序号</td>
            <td class="label value">姓名</td>
            <td class="label">关系</td>
            <td class="label value">联系电话</td>
          </tr>
          <tr>
            <td class="label-white">1</td>
            <td class="value">赵明</td>
            <td class="label-white">父子</td>
            <td class="value">13685968846</td>
          </tr>
        </table>
        <table v-if="currentStep === 3" class="ma-table">
          <tr class="ma-table-title">
            <td colspan="6" style="border-top: none">处理结果</td>
          </tr>
          <tr>
            <td class="label">处理方式</td>
            <td class="value">{{
              dataAlarm.handleMethod ? dataAlarm.handleMethod : '无'
            }}</td>
            <td class="label">处理结果</td>
            <td class="value">{{
              dataAlarm.handleResult ? dataAlarm.handleResult : '无'
            }}</td>
          </tr>
          <tr>
            <td class="label">补充说明</td>
            <td class="value" colspan="5">
              <span v-if="additions.length === 0">无</span>
            </td>
          </tr>
          <tr>
            <td class="label">现场图片</td>
            <td class="value" colspan="5">
              <span v-if="siteImages.length === 0">无</span>
            </td>
          </tr>
        </table>
      </a-skeleton>
    </div>
    <div class="m-alarm-d-btns">
      <div style="width: 1020px; text-align: right">
        <a-space>
          <a-button v-if="currentStep === 1" @click="drawerHandler.show"
            >关闭工单</a-button
          >
          <a-button v-if="currentStep !== 3" type="primary" disabled
            >查看现场</a-button
          >
        </a-space>
      </div>
    </div>
    <a-drawer
      :width="400"
      :visible="drawerHandler.visible"
      unmount-on-close
      @ok="drawerHandler.onOk"
      @cancel="drawerHandler.onCancel"
    >
      <template #title>关闭工单</template>
      <div>
        <a-form v-bind="dataForm.bindProps" layout="vertical">
          <a-form-item
            :field="baseNameMap.handleMethod.key"
            :label="baseNameMap.handleMethod.label"
            required
          >
            <a-input
              v-model="dataForm.state[baseNameMap.handleMethod.key]"
              :placeholder="baseNameMap.handleMethod.placeholder"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.handleResult.key"
            :label="baseNameMap.handleResult.label"
            required
          >
            <a-input
              v-model="dataForm.state[baseNameMap.handleResult.key]"
              :placeholder="baseNameMap.handleResult.placeholder"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.images.key"
            :label="baseNameMap.images.label"
          >
            <a-upload v-bind="uploader.props" @change="uploader.handleChange" />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.addtions.key"
            :label="baseNameMap.addtions.label"
          >
            <a-textarea
              v-model="dataForm.state[baseNameMap.addtions.key]"
              style="height: 80px"
              :placeholder="baseNameMap.addtions.placeholder"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-space>
          <a-button @click="drawerHandler.onCancel()">
            <template #icon><icon-close-circle /></template>
            <template #default>取消</template>
          </a-button>
          <a-button type="primary" @click="drawerHandler.onOk()">
            <template #icon><icon-save /></template>
            <template #default>确定</template>
          </a-button>
        </a-space>
      </template>
    </a-drawer>
    <DispatchOrder v-bind="dispatchOrderHandler.bindProps" />
  </div>
</template>

<style lang="less" scoped>
  .m-alarm-details {
    height: 100%;
  }

  .m-alarm-d-body {
  }

  .ma-table {
    width: 1020px;
    text-align: center;
    color: var(--color-text-1);

    td {
      border: 2px solid var(--color-neutral-4);
      padding: 10px 20px;
      box-sizing: border-box;
    }
    .label {
      width: 170px;
      background-color: var(--color-neutral-3);
    }
    .label-white {
      width: 170px;
    }
    .value {
      width: 340px !important;
    }
  }

  .ma-table-title {
    padding: 10px 0;
    font-weight: 600;
    font-size: 16px;
  }

  .m-alarm-d-btns {
    width: 100%;
    text-align: right;
    padding: 15px 0;
    border-top: 2px solid var(--color-neutral-3);
    display: flex;
    justify-content: center;
  }
</style>
